#!/usr/bin/env python3
"""
AWS SDK C++ MCP Server

面向软件：aws-sdk-cpp
提供 AWS SDK for C++ 命令行操作的 MCP 工具封装

MCP tools 列表：
1. aws_sdk_cpp_check_installation - 检查 aws-sdk-cpp 包是否已安装
   参数：无
   返回：包含安装检查结果的 JSON

2. aws_sdk_cpp_compile_test - 编译 AWS SDK C++ 测试程序
   参数：
     - source_file: 源文件路径
     - output_name: 输出可执行文件名
     - work_dir: 工作目录路径
   返回：包含编译结果的 JSON

3. aws_sdk_cpp_run_test - 运行编译后的测试程序
   参数：
     - executable: 可执行文件路径
     - test_args: 测试参数列表
     - expected_output: 期望的输出内容
   返回：包含测试运行结果的 JSON
"""

import subprocess
import json
from typing import List
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("AWS SDK C++ MCP Server")

@mcp.tool()
def aws_sdk_cpp_check_installation() -> dict:
    """
    检查 aws-sdk-cpp 包是否已安装
    
    返回：
        dict: 包含检查结果的 JSON
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    command = ["rpm", "-qa", "aws-sdk-cpp"]
    
    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0 and "aws-sdk-cpp" in result.stdout,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Error executing command: {str(e)}"
        }

@mcp.tool()
def aws_sdk_cpp_compile_test(source_file: str, output_name: str, work_dir: str = "/tmp") -> dict:
    """
    编译 AWS SDK C++ 测试程序
    
    参数：
        source_file: C++ 源文件路径
        output_name: 输出可执行文件名
        work_dir: 工作目录路径，默认为 /tmp
    
    返回：
        dict: 包含编译结果的 JSON
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    compile_command = [
        "g++", 
        "-D_GLIBCXX_USE_CXX11_ABI=0", 
        source_file, 
        "-o", output_name,
        "-laws-cpp-sdk-core", 
        "-laws-cpp-sdk-s3"
    ]
    
    try:
        result = subprocess.run(
            compile_command,
            cwd=work_dir,
            capture_output=True,
            text=True,
            timeout=60
        )
        
        # 检查编译后的文件是否存在
        check_command = ["test", "-e", output_name]
        check_result = subprocess.run(
            check_command,
            cwd=work_dir,
            capture_output=True,
            text=True
        )
        
        success = result.returncode == 0 and check_result.returncode == 0
        
        return {
            "success": success,
            "command": " ".join(compile_command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(compile_command),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Compilation timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(compile_command),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Error during compilation: {str(e)}"
        }

@mcp.tool()
def aws_sdk_cpp_run_test(executable: str, test_args: List[str] = None, expected_output: str = None) -> dict:
    """
    运行编译后的 AWS SDK C++ 测试程序
    
    参数：
        executable: 可执行文件路径
        test_args: 测试参数列表，默认为 None
        expected_output: 期望的输出内容，用于验证测试结果
    
    返回：
        dict: 包含测试运行结果的 JSON
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    if test_args is None:
        test_args = []
    
    command = [executable] + test_args
    
    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        # 如果提供了期望的输出内容，检查是否匹配
        output_matched = True
        if expected_output and expected_output not in result.stdout:
            output_matched = False
        
        success = result.returncode == 0 and output_matched
        
        return {
            "success": success,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Test execution timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Error during test execution: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()